<script setup lang="ts">
import type { SessionType } from '~/types/chat'

const { showToast } = useToast();
const { getSessionList } = useChat();
const route = useRoute();

const sessionList = ref<Array<SessionType>>();

const page = ref(1);

const pageCount = ref(1);

const loading = ref(false);

// jump to index
const onNewChat = async () => {
    await navigateTo({ path: '/home/chat' });
    showToast({ msg: 'Choose a template to start!', type: 'success' });
};

// get session list
const onFetchSessions = async (pageNumber?: number) => {
    const { code, data: { list, ...pageParams } } = await getSessionList({ page: pageNumber || page.value, itemPerPage: 8 });
    if (code === 0) {
        // refresh data
        sessionList.value = list;
        page.value = pageParams.page;
        pageCount.value = pageParams.pageCount;
    }
};

defineExpose({ refresh: onFetchSessions, current: computed(() => sessionList.value?.find(s => s.id === route.params.id)) });

// refresh session list
watch(() => route.params.id, () => {
    onFetchSessions();
});

// init session list
onMounted(() => {
    onFetchSessions();
});
</script>

<template>
    <nav class="relative p-4 w-80 h-full shrink-0 border-r-2 border-slate-100 flex flex-col gap-4 items-center">
        <header class="w-full text-xl flex justify-between items-center">
            Message List
            <div class="flex gap-2">
                <button
                    class="p-2 w-8 h-8 border border-element shadow active:shadow-inner rounded-md flex justify-center items-center"
                    @click="onNewChat">
                    <svg class="icon aspect-square shrink-0" :style="{ width: '100%' }" aria-hidden="true">
                        <use xlink:href="#icon-plus" />
                    </svg>
                </button>
                <button
                    class="p-2 w-8 h-8 bg-element rounded-md shadow active:shadow-inner flex justify-center items-center"
                    @click="() => onFetchSessions()">
                    <svg class="icon aspect-square shrink-0 transition hover:duration-1000 hover:rotate-[720deg]"
                        :style="{ width: '100%' }" aria-hidden="true">
                        <use xlink:href="#icon-refresh-white" />
                    </svg>
                </button>
            </div>
        </header>
        <ol class="w-full flex-auto flex flex-col gap-2">
            <home-chat-message-list-item v-for="s in sessionList" :key="s.id" :title="s.title" :content="s.content"
                :to="`/home/chat/${s.id}`" />
        </ol>
        <c-pagination :page="page" :page-count="pageCount" :loading="loading"
            @change="pageNumber => onFetchSessions(pageNumber)" @prev="onFetchSessions(page - 1)"
            @next="onFetchSessions(page + 1)" />
    </nav>
</template>